package com.etc.threaddemo.ticket;

import java.util.Random;

/**
 * 卖票
 * 
 * @author Administrator
 *
 */
public class TicketRunnable implements Runnable {

	// 卖100张(数据共享的)
	private int ticketCount = 100;

	// 定义一个方法执行卖票的操作
	private synchronized   void saleTicket() {
		// 判断一下 1
		// 
		if (ticketCount > 0) {
			// Thread.currentThread() 线程对象
			Thread th = Thread.currentThread();
			// ticketCount-- 每次--
			System.out.println(th.getId() + "," + th.getName() + "正在卖第" + ticketCount-- + "张卖票");

			// 每次卖票需要花费一定的时间
			try {
				Thread.sleep(new Random().nextInt(30));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		// 调用saleTicket方法
		while (ticketCount > 0) {
			saleTicket();
		}
	}

}